# -*- coding: utf-8 -*-
import math

from flask import Blueprint, request, jsonify, json
from application import db
from common.models.article import Article
import uuid
from operator import and_, __or__, or_
from common.libs.queryToDict import *
from werkzeug.utils import secure_filename
from common.models.user import User
from common.models.article_category import ArticleCategory
from common.models.article_category_mapping import ArticleCategoryMapping
from config.base_setting import IMG_PATH
from datetime import datetime, date
import os

route_article = Blueprint('route_article', __name__)


# 获取文章列表信息
@route_article.route("/get_article_list", methods=["GET", "POST"])
def get_article_list():
    resp = {"err": "0", "errMsg": "", "data": ""}
    article = Article()
    in_vo = request.get_json()
    filter = []
    # 一页多少条
    page_size = in_vo["page_size"]
    # 第几页
    page_index = in_vo["page_index"]
    filter.append(Article.del_flag == 0)

    # 根据用户权限查看的数据不同
    if "user_id" in in_vo:
        user_id = in_vo["user_id"]
        user = User.query.filter(User.user_Id == user_id).first()
        if user.user_type == "2":
            if "article_model" in in_vo:
                article.article_model = in_vo["article_model"]
                filter.append(__or__(Article.user_id == user_id, Article.article_model == article.article_model))
            else:
                filter.append(Article.user_id == user_id)
        elif user.user_type == "3":
            # 文章模式
            if "article_model" in in_vo:
                article.article_model = in_vo["article_model"]
                filter.append(Article.article_model == article.article_model)
    else:
        if "article_model" in in_vo:
            article.article_model = in_vo["article_model"]
            filter.append(Article.article_model == article.article_model)

    # 关键词查询
    if "select_word" in in_vo:
        article.select_word = in_vo["select_word"]
        filter.append(or_(or_(Article.article_content.like('%' + article.select_word + '%'),
                              Article.title.like('%' + article.select_word + '%')),
                          (Article.summary.like('%' + article.select_word + '%'))))
    if "category_id" in in_vo:
        category_id = in_vo["category_id"]
        filter.append(ArticleCategoryMapping.category_id == category_id)

    if "article_category_id" in in_vo:
        article_category_id = in_vo["article_category_id"]
        filter.append(Article.article_sub_categorys.like("%" + article_category_id + '%'))

    # filter.append(or_(Article.summary.like('%' + article.select_word + '%')))
    # filter.append(Article.title == article.select_word)

    # res_list = Article.query.filter(*filter).limit(
    #     page_size).offset(
    #     (page_index - 1) * page_size).all()

    # if res_list:
    #     resp["data"] = query_to_dict(res_list)
    paginates = Article.query.outerjoin(ArticleCategoryMapping,
                                        ArticleCategoryMapping.article_id == Article.article_id).filter(
        *filter).order_by(Article.create_time.desc()).paginate(page_index, page_size,
                                                               error_out=False)

    items = paginates.items
    # total为总页面数
    total = math.ceil(paginates.total)
    if items:
        resp["data"] = query_to_dict(items)
        resp["total"] = total
    return jsonify(resp)


# 上传图片
@route_article.route("/upload", methods=["GET", "POST"])
def upload():
    resp = {"code": "200", "errMsg": "",
            "data": {"url": ""}}
    http_url_path = IMG_PATH  # "http://127.0.0.1:8999/"
    # 文件对象保存在request.files上，并且通过前端的input标签的name属性来获取
    fp = request.files.get("img")

    base_path = os.path.dirname(__file__)  # 当前文件所在路径
    http_url = os.path.join(http_url_path, 'static', secure_filename(fp.filename))
    resp["data"]["url"] = http_url
    # upload_path = os.path.join(base_path, 'static/images', secure_filename(fp.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    upload_path = os.path.join('web/static', secure_filename(fp.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    # 保存文件到服务器本地
    fp.save(upload_path)
    return jsonify(resp)


# 上传图片
@route_article.route("/upload_icon", methods=["GET", "POST"])
def upload_icon():
    resp = {"code": "200", "errMsg": "",
            "data": {"url": ""}}
    http_url_path = IMG_PATH  # "http://127.0.0.1:8999/"
    # 文件对象保存在request.files上，并且通过前端的input标签的name属性来获取
    fp = request.files.get("file")

    base_path = os.path.dirname(__file__)  # 当前文件所在路径
    http_url = os.path.join(http_url_path, 'static', secure_filename(fp.filename))
    resp["data"]["url"] = http_url
    # upload_path = os.path.join(base_path, 'static/images', secure_filename(fp.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    upload_path = os.path.join('web/static', secure_filename(fp.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    # 保存文件到服务器本地
    fp.save(upload_path)
    return jsonify(resp)


# 根据id获取文章信息
@route_article.route("/select_article", methods=["GET", "POST"])
def select_article():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    # 文章Id
    article_id = "" if in_vo["article_id"] is None else in_vo["article_id"]

    article = Article.query.filter(Article.article_id == article_id).first()
    if article.view_count is None:
        article.view_count
    else:
        article.view_count += 1
    # 提交
    db.session.commit()
    resp["data"] = query_to_dict(article)
    return jsonify(resp)


# 添加文章
@route_article.route("/insert_article", methods=["GET", "POST"])
def insert_article():
    in_vo = request.get_json()
    # 添加文章
    article = Article()
    article.article_id = uuid.uuid4()
    article.blog_id = uuid.uuid4()
    article.title = in_vo["title"]
    article.article_content = in_vo["article_content"]

    if "article_sub_category" in in_vo:
        article.article_sub_category = in_vo["article_sub_category"]

    if "article_sub_categorys" in in_vo:
        article.article_sub_categorys = in_vo["article_sub_categorys"]

    if "user_id" in in_vo:
        article.user_id = in_vo["user_id"]

    article.meta_keywords = in_vo["meta_keywords"]
    article.article_model = in_vo["article_model"]
    article.summary = in_vo["summary"]
    if "link_to" in in_vo:
        article.link_to = in_vo["link_to"]
    article.del_flag = 0
    article.view_count = 0
    article.create_time = datetime.now()
    article.comment_time = datetime.now()
    article.update_time = datetime.now()
    article.article_Type = in_vo["article_category"]
    db.session.add(article)
    article_category_mapping = ArticleCategoryMapping()
    article_category_mapping.article_id = article.article_id
    article_category_mapping.category_id = in_vo["article_category"]
    db.session.add(article_category_mapping)

    # 提交
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)


# 逻辑删除文章
@route_article.route("/update_delete_flag_article", methods=["GET", "POST"])
def update_delete_flag_article():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    article_id = in_vo["article_id"]
    article = Article.query.filter(Article.article_id == article_id).first()
    article.del_flag = "1"
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)


# 更新文章
@route_article.route("/update_article", methods=["GET", "POST"])
def update_article():
    in_vo = request.get_json()
    article_id = in_vo["article_id"]
    article = Article.query.filter(Article.article_id == article_id).first()
    article.title = in_vo["title"]
    article.article_content = in_vo["article_content"]
    article.meta_keywords = in_vo["meta_keywords"]
    article.article_model = in_vo["article_model"]
    article.summary = in_vo["summary"]
    article.del_flag = 0
    if "user_id" in in_vo:
        article.user_id = in_vo["user_id"]
    article.update_time = datetime.now()

    if "article_sub_category" in in_vo:
        article.article_sub_category = in_vo["article_sub_category"]

    if "article_sub_categorys" in in_vo:
        article.article_sub_categorys = in_vo["article_sub_categorys"]

    if "link_to" in in_vo:
        article.link_to = in_vo["link_to"]

    article_category_mapping = ArticleCategoryMapping.query.filter(
        ArticleCategoryMapping.article_id == article_id).first()
    if article_category_mapping is not None:
        article_category_mapping.category_id = in_vo["article_category"]
    else:
        article_category_mapping = ArticleCategoryMapping()
        article_category_mapping.article_id = article.article_id
        article_category_mapping.category_id = in_vo["article_category"]
        db.session.add(article_category_mapping)
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)


# 点赞文章
@route_article.route("/update_article_like", methods=["GET", "POST"])
def update_article_like():
    in_vo = request.get_json()
    article_id = in_vo["article_id"]
    article = Article.query.filter(Article.article_id == article_id).first()
    article.article_like_num = in_vo["article_like_num"]
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)
